/**
 * 处理防护的 插件
 * @param {*} ctx 
 * @param {*} next 
 */
const baseConfig = require('../config/base');
module.exports = async (ctx, next) => {
    if (baseConfig.isOpenDefense) {
        let cip = ctx.fun.getClientIp();
        if (!cip) ctx._throw(412, 'Your information is incomplete');

        if (cache.has(`defense_ban_${cip}`)) {
            ylog.warn(`IP: ${cip} malicious request, please wait and try again!`);
            ctx._throw(403, 'malicious request, please wait and try again!');
        }
        const defenseKey = `defense_${cip}`;
        let ipNum = cache.get(defenseKey);
        if (ipNum) {
            if (ipNum.num >= baseConfig.defense.numberRequests) {
                cache.set(`defense_ban_${cip}`, true, baseConfig.defense.banTime);
                ylog.warn(`ban ${cip} Because of malicious access!`);
                ctx._throw(403, 'malicious request, please wait and try again!');
            }
            ipNum.num++;
            let defenseKeyTtl = baseConfig.defense.interval-(parseInt(Date.now() / 1000) - ipNum.time);//得到剩余时间
            cache.set(defenseKey, ipNum, defenseKeyTtl);
        } else {
            cache.set(defenseKey, { num: 1, time: parseInt(Date.now() / 1000) }, baseConfig.defense.interval);
        }
    }
    await next();
}
